package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.RequisitionListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DictionaryTreeContent;
import com.isunland.managesystem.entity.RequisitionSimpleOriginal;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;

public class CheckListFragment extends BaseListFragment {
  protected static final String EXTRA_VALUE =
      "com.isunland.managesystem.ui.CheckListFragment.EXTRA_VALUE";
  private static final int REQUEST_ADD = 0;
  private static final int REQUEST_DETAIL = 1;
  private static final int REQUEST_SEARCH = 2;
  private ArrayList<RequisitionSimpleOriginal> mRequisitionList;
  private RequisitionListAdapter mAdapter;
  private CustomerDialog mDataStatus;
  private CustomerDialog mVacatioType;
  private String mdataStatusMobile;
  private BaseVolleyActivity mActivity;
  //    private CustomerDialog extraContent;
  private String mjobNo;
  private String mrecordDate;
  public static final HashMap<String, String> mapOffType = new HashMap<>();
  //调休类型map,key:code,value：名字

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    //mListview.setDividerHeight(0);
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      if (NavUtils.getParentActivityName(mActivity) != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
      }
      actionBar.setTitle(R.string.requisition);
    }
    //        extraContent = (CustomerDialog) getArguments().getSerializable(EXTRA_VALUE);
    //        if (extraContent != null) {
    //            //考勤汇总单据明细
    //            mjobNo = extraContent.getId();
    //            mrecordDate = extraContent.getName();
    //            mdataStatusMobile = "T";
    //        } else {
    mjobNo = CurrentUser.newInstance(getActivity()).getJobNumber();
    mrecordDate = "";
    mdataStatusMobile = "";
    //        }
    //获取调休类型
    volleyOffType();
    super.onCreate(savedInstanceState);
  }

  private void volleyOffType() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DATA_DICTIONARY_LIST);
    HashMap<String, String> params = new HashMap<>();
    params.put("dictFlg", "hrHolyKindCode");
    params.put("memCode", CurrentUser.newInstance(getActivity()).getMemberCode());
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        DictionaryTreeContent[] dataList = new Gson().fromJson(arg0, DictionaryTreeContent[].class);
        for (DictionaryTreeContent aDataList : dataList) {
          mapOffType.put(aDataList.getCustomAttrs(), aDataList.getName());
        }
      }
    });
  }

  /**
   * 获取考勤列表不需要传参数，查询的时候需要传
   */
  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    if (mDataStatus != null && mDataStatus.getId() != null) {
      params.put("dataStatus", mDataStatus.getId());
    }
    if (mVacatioType != null && mVacatioType.getId() != null) {
      params.put("type", mVacatioType.getId());
    }
    params.put("recordDate", mrecordDate);
    params.put("jobNo", mjobNo);
    params.put("dataStatusMobile", mdataStatusMobile);//考勤汇总详情中单据明细列表为“T”,考勤申请单为空
    params.put("ifNewOver", "2");//目的是兼容老版本:1,过滤新的加班;2,过滤新的加班和外出
    return params;
  }

  @Override public String getUrl() {

    return ApiConst.URL_REQUISITION_LIST;
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    RequisitionSimpleOriginal requisitionSimpleOriginal = mRequisitionList.get(position - 1);
    String type = requisitionSimpleOriginal.getAttendType();
    String reId = requisitionSimpleOriginal.getId();
    String dataStatus = requisitionSimpleOriginal.getDataStatus();
    String ifAllowSupplement = requisitionSimpleOriginal.getIfAllowSupplement();
    //考勤汇总单据明细的考勤申请列表，目的隐藏掉可以操作的菜单
    //        if (extraContent != null) {
    //            dataStatus = DataStatus.CHECK_PASS;
    //        }
    String runId = "";
    if ("waitCheck".equalsIgnoreCase(dataStatus)) {
      runId = requisitionSimpleOriginal.getRunId();
    }

    String file = "";
    if ("holy".equalsIgnoreCase(type)) {
      file = requisitionSimpleOriginal.getAccessoryName();
    }
    if ("overnew".equalsIgnoreCase(type)) {
      //新加班单
      Intent over = new Intent(getActivity(), CheckOverPagerActivity.class);
      over.putExtra(CheckOverMainFragment.EXTRA_CONTENT, requisitionSimpleOriginal);
      //over.putExtra(CheckOutMainFragment.EXTRA_CONTENT, requisitionSimpleOriginal);
      startActivityForResult(over, REQUEST_DETAIL);
    } else if ("outnew".equals(type)) {
      //新外出单
      Intent out = new Intent(getActivity(), CheckOutPagerActivity.class);
      out.putExtra(CheckOutMainFragment.EXTRA_CONTENT, requisitionSimpleOriginal);
      startActivityForResult(out, REQUEST_DETAIL);
    } else {
      startCheckDetail(type, reId, runId, file, dataStatus, ifAllowSupplement);
    }
    super.onListItemClick(l, v, position, id);
  }

  /**
   * @param type 类型
   * @param reId 用于初始化数据.
   */
  private void startCheckDetail(String type, String reId, String runId, String file,
      String dataStatus, String ifAllowSupplement) {
    Intent i = new Intent(getActivity(), CheckDetailActivity.class);
    i.putExtra(CheckDetailFragment.EXTRA_REQUISITION_ID, reId);
    i.putExtra(CheckDetailFragment.EXTRA_TYPE, type);
    i.putExtra(CheckDetailFragment.EXTRA_INTERRUPT, runId);
    i.putExtra(CheckDetailFragment.EXTRA_FILE, file);
    i.putExtra(CheckDetailFragment.EXTRA_DATASTATUS, dataStatus);
    i.putExtra(CheckDetailFragment.EXTRA_IFALLOW, ifAllowSupplement);
    startActivityForResult(i, REQUEST_DETAIL);
  }

  @Override public void resolveResponse(String arg0) {

    Type listType = new TypeToken<ArrayList<RequisitionSimpleOriginal>>() {
    }.getType();
    ArrayList<RequisitionSimpleOriginal> requisitionList = new Gson().fromJson(arg0, listType);

    setAdapter(requisitionList);
  }

  private void setAdapter(ArrayList<RequisitionSimpleOriginal> requisitionList) {
    if (mRequisitionList == null) {
      mRequisitionList = new ArrayList<>();
    }
    mRequisitionList.clear();
    mRequisitionList.addAll(requisitionList);

    if (mAdapter == null) {
      mAdapter = new RequisitionListAdapter(mActivity, mRequisitionList);
      setListAdapter(mAdapter);
    }
    ((RequisitionListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    //        if (extraContent == null) {
    inflater.inflate(R.menu.menu_add_search, menu);
    //        } else {
    //            super.onCreateOptionsMenu(menu, inflater);
    //        }

  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      /**
       * 响应返回按钮
       */
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_add:
        FragmentManager fm = getActivity().getSupportFragmentManager();
        RequisitionChooseDialogFragment dialog = new RequisitionChooseDialogFragment();
        dialog.setTargetFragment(CheckListFragment.this, REQUEST_ADD);
        dialog.show(fm, "");
        return true;

      case R.id.menu_item_querys:
        Intent intent = new Intent(getActivity(), RequisitionListSearchActivity.class);
        intent.putExtra(RequisitionListSearchFragment.EXTRA_DATASATUS, mDataStatus);
        intent.putExtra(RequisitionListSearchFragment.EXTRA_VACATION_TYPE, mVacatioType);
        startActivityForResult(intent, REQUEST_SEARCH);
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  /**
   * 添加的时候刷新调用. 因为添加是通过dialog添加的,所以dialog中用getActivity.startActivity()启动新的界面,
   * 这样就会走下面的方法. 在方法中判断请求码为添加且结果马为成功时刷新列表.
   */
  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_ADD) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      String type = customer.getId();
      String ifAllowSupplement = customer.getJobNo();

      if (CheckDetailFragment.VALUE_OVER.equals(type)) {
        /**新版加班申请*/
        Intent over = new Intent(getActivity(), CheckOverPagerActivity.class);
        over.putExtra(CheckOverMainFragment.EXTRA_IFALLOWSUPPLEMENT, ifAllowSupplement);
        //over.putExtra(CheckOutMainFragment.EXTRA_IFALLOWSUPPLEMENT, ifAllowSupplement);
        startActivityForResult(over, REQUEST_DETAIL);
      } else if (CheckDetailFragment.VALUE_OUT.equals(type)) {
        /**新版外出申请*/
        Intent out = new Intent(getActivity(), CheckOutPagerActivity.class);
        out.putExtra(CheckOutMainFragment.EXTRA_IFALLOWSUPPLEMENT, ifAllowSupplement);
        startActivityForResult(out, REQUEST_DETAIL);
      } else {
        /**其他类型申请单*/
        startCheckDetail(type, "", "", "", "", ifAllowSupplement);
      }
      return;
    }
    if (requestCode == REQUEST_SEARCH) {
      mDataStatus =
          (CustomerDialog) data.getSerializableExtra(RequisitionListSearchFragment.EXTRA_DATASATUS);
      mVacatioType = (CustomerDialog) data.getSerializableExtra(
          RequisitionListSearchFragment.EXTRA_VACATION_TYPE);
    }
    volleyPost();
    super.onActivityResult(requestCode, resultCode, data);
  }

  public static CheckListFragment newInstance(CustomerDialog extraContent) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_VALUE, extraContent);
    CheckListFragment fragment = new CheckListFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
